package com.cqh.recruit.controller.student;


import com.cqh.recruit.pojo.dto.StudentLoginDTO;
import com.cqh.recruit.pojo.dto.UpdatePasswordDTO;
import com.cqh.recruit.pojo.entity.LoginInfo;
import com.cqh.recruit.result.Result;
import com.cqh.recruit.service.IStudentService;
import com.cqh.recruit.utils.JwtUtils;
import com.cqh.recruit.utils.StudentThreadLocal;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Author: DengHao
 * @Date: 2025/10/18 10:13
 */
@RestController
@RequestMapping("/api/student/stuLogin")
@Tag(name = "学生登录接口")
public class StudentLoginController {

    @Autowired
    private IStudentService studentService;

    /**
     * 学生登录
     * @param student
     * @return Result
     */
    @PostMapping("/login")
    @Operation(summary = "学生登录")
    public Result login(@RequestBody StudentLoginDTO student){
        LoginInfo info = studentService.login(student);
        if (info == null) {
            return Result.buildFail(40001, "用户名或密码错误!");
        }
        return Result.buildSuccess(info);
    }

    @PostMapping("/updatePassword")
    @Operation(summary = "修改密码")
    public Result updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDto, HttpServletRequest request){
        // 从请求头中获取token
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return Result.buildFail(null, "用户未登录");
        }
        
        try {
            // 解析token获取用户信息
            Claims claims = JwtUtils.parseToken(token);
            Long stuId = ((Integer) claims.get("stuId")).longValue();
            
            // 调用service方法修改密码，传递用户ID
            studentService.updatePassword(updatePasswordDto, stuId);
            return Result.buildSuccess("修改密码成功");
        } catch (Exception e) {
            return Result.buildFail(null, "用户未登录或令牌已过期");
        }
    }
    
    /**
     * 学生退出登录
     * @return Result
     */
    @PostMapping("/logout")
    @Operation(summary = "学生退出登录")
    public Result logout() {
        // 清除当前线程中的用户信息
        StudentThreadLocal.remove();
        return Result.buildSuccess("退出登录成功");
    }

}